<%@page import="csci5828.servlet.RequestAttributes"%>
<%@page import="csci5828.tasks.RequestId"%>
<%
RequestId requestId = (RequestId)request.getAttribute("requestId");
java.util.Date date = new java.util.Date(); 
Boolean cityChk = (Boolean)request.getAttribute("chkCityGrid");
Boolean yelpChk = (Boolean)request.getAttribute("chkYelp");
String query = (String)request.getAttribute("query");
String location = (String)request.getAttribute("location");
%>
<html>
  <head>
    <title>Comet Reviews</title>
    <link href="style/style.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="scripts/util.js"></script>
    <script type="text/javascript" src="scripts/prototype.js"></script>
    <script type="text/javascript" src="scripts/scriptaculous.js"></script>
    <script type="text/javascript" src="scripts/effects.js"></script>
    <script type="text/javascript" src="scripts/spin.js"></script>
    <script type="text/javascript">
// Structure of map is as follows:
/*
{"availResults": 
	[
	 	{
	 		"sourceName":"CityGrid",
	 		"elapsed":0.022,
	 		"results":
	 		[
	 			{
	 				"source":"Judy\u0027sBook",
	 				"sourceRank":"10",
	 				"rating":"10",
	 				"url":"http://www.judysbook.com/members/18366/posts/2005/8/142739/",
	 				"text":"When our kitten had an allergic reaction to her rabies shot...",
	 				"qualityScore":0.0
	 			},
	 			{
	 				"source":"CITYSEARCH",
	 				"sourceRank":"2",
	 				"rating":"2",
	 				"url":"http://boulder.citysearch.com/review/1864398?reviewId\u003d161542341",
	 				"text":"I have brought my pups to Cottonwood for a few years now, ever since..",
	 				"qualityScore":0.0
	 			},
	 			...
	 		]
	 	},
	 	{
	 		"sourceName":"Yelp",
	 		"results": [ ... ]
	 	}
	 ],
 "waitResult":
	 	{
	 		"sourceName":"Yelp",
	 		"elapsed":0.022,
	 		"results":
	 		[
	 			{
	 				"source":"Judy\u0027sBook",
	 				"sourceRank":"10",
	 				"rating":"10",
	 				"url":"http://www.judysbook.com/members/18366/posts/2005/8/142739/",
	 				"text":"When our kitten had an allergic reaction to her rabies shot...",
	 				"qualityScore":0.0
	 			},
	 			{
	 				"source":"CITYSEARCH",
	 				"sourceRank":"2",
	 				"rating":"2",
	 				"url":"http://boulder.citysearch.com/review/1864398?reviewId\u003d161542341",
	 				"text":"I have brought my pups to Cottonwood for a few years now, ever since..",
	 				"qualityScore":0.0
	 			},
	 			...
	 		]
	 	}
 "done":true
}
    
      <div class="result">
        <div class="sourceimage">
          <img src="images/citygrid.png"/>
        </div>
        <div class="sourceresults">
        <div class="primaryresults">
            <div class=sourceresult">
                <span class="businessname">Cottonwood Kennels</span>
                <span class="review">This place sucks; why would you do this to your pet?</span>
                <span class="rating">5</span>
             </div>
        </div>
        <div class="secondaryresults">
            <div class=sourceresult">
                <span class="businessname">Cottonwood Kennels</span>
                <span class="review">This place sucks; why would you do this to your pet?</span>
                <span class="rating">5</span>
            </div>
        </div>
        </div>
      </div>
*/
function buildListItem(res) {
	// some variables from the map
	var elapsed = res["elapsed"];
	var resultsarr = res["results"];
	var sourceName = res["sourceName"];
	
	// construct our container DOM elements
	var group = new Element('div', {'class': 'result'});
	var sourceimage = new Element('div', {'class': 'sourceimage'});
	var img = new Element('img', {'src': 'images/' + sourceName.toLowerCase() + '.png'});
	sourceimage.appendChild(img);
	group.appendChild(sourceimage);
	var sourceresults = new Element('div', {'class':'sourceresults'});
	group.appendChild(sourceresults);
    var primary = new Element('div', {'class':'primaryresults'});
    var secondary = new Element('div', {'class':'secondaryresults', 'id':'bar'+sourceName});
    var toggle = new Element('div', 
    		{'class':'togglebar', 'onclick':"Effect.toggle('bar"+sourceName+"', 'blind')"});
    secondary.hide();
    sourceresults.appendChild(primary);
    sourceresults.appendChild(secondary);
    if(resultsarr.length > 5)
    {
    	sourceresults.appendChild(toggle);	
    }
    
	console.log(sourceName);
	group.appendChild(document.createComment(elapsed));
	if (resultsarr.length > 0) {
    	for (var j=0; j<5 && j<resultsarr.length; j++) {
    		var result = resultsarr[j];
    		var item = new Element('div', {'class':'sourceresult'});
  
    		var spanbusiness = new Element('span', {'class':'businessname'});
    		spanbusiness.appendChild(document.createTextNode(result["businessName"]));
    		var spanreview = new Element('span', {'class':'review'});
    		spanreview.appendChild(document.createTextNode(result["text"]));
         var spanrating = new Element('span', {'class':'rating'});
         spanrating.appendChild(document.createTextNode("[Rating: "));
         spanrating.appendChild(document.createTextNode(result["normalizedRating"]));
         spanrating.appendChild(document.createTextNode("]"));
    		item.appendChild(spanbusiness);
    		item.appendChild(spanrating);
    		item.appendChild(spanreview);
    		primary.appendChild(item);
    	}
    	for (var j=5; j<resultsarr.length; j++) {
            var result = resultsarr[j];
            var item = new Element('div', {'class':'sourceresult'});
     
            var spanbusiness = new Element('span', {'class':'businessname'});
            spanbusiness.appendChild(document.createTextNode(result["businessName"]));
            var spanreview = new Element('span', {'class':'review'});
            spanreview.appendChild(document.createTextNode(result["text"]));
            var spanrating = new Element('span', {'class':'rating'});
            spanrating.appendChild(document.createTextNode("[Rating: "));
            spanrating.appendChild(document.createTextNode(result["normalizedRating"]));
            spanrating.appendChild(document.createTextNode("]"));
            item.appendChild(spanbusiness);
            item.appendChild(spanrating);
            item.appendChild(spanreview);
            secondary.appendChild(item);
         }    	
	} else {
		sourceresults.appendChild(document.createTextNode("no results"));
	}
	return group;
}

function buildResults(output, firstLoad, stopAnimation) {
	var div = Element.extend(document.createElement('div'));
	div.hide();
	console.log(output);
	
	if ("availResults" in output) {
    	var availResultsArr = output["availResults"];
    	console.log("results="+results);
    	for (var i=results; i<availResultsArr.length; i++) {
    		var group = buildListItem(availResultsArr[i]);
    		console.log("adding available item #"+i);
    		div.appendChild(group);
    		results++;
    	}
	}
	
	if ("waitResult" in output) {
    	var waitResult = output["waitResult"];
    	var waitGroup = buildListItem(waitResult);
  		console.log("adding waitResult item");
    	div.appendChild(waitGroup);
    	results++;
	}
	
	if (firstLoad) {
		$('results').replaceChild(div, $('results').firstChild);
		div.appear();
	} else {
    	$('results').appendChild(div);
		div.appear();
	}
	if (stopAnimation) {
		spinner.stop();
	}
}
    
    
function handleResponse() {
	if (xmlhttp.readyState == 4) {
		var json = xmlhttp.responseText;
		eval('output = '+ json);  // yeah, we should probably use a JSON parser here.
		if (("done" in output) && output["done"]) {
			//alert('done');
       		buildResults(output, firstload, true);
        	return;
		} else if (requests > 10) {
			alert('limit');
       		buildResults(output, firstload, true);
        	return;
        }
       	buildResults(output, firstload, false);
       	xmlhttp.abort();
		firstload = false;
      	sendXmlHttpRequest();
	}
}

function sendXmlHttpRequest() {
    xmlhttp.onreadystatechange = handleResponse;
    var url = "lpresults?requestId=<%=requestId.getId()%>";
    if (!firstload) {
    	url = url + "&wait=True";
    }
    console.log(url);
    xmlhttp.open("GET", url);
    xmlhttp.send(null);
    requests++;
}
    
window.onload = function() {
	var opts = {
		lines: 13, // The number of lines to draw
		length: 9, // The length of each line
        width: 4, // The line thickness
        radius: 8, // The radius of the inner circle
        rotate: 0, // The rotation offset
        color: '#000', // #rgb or #rrggbb
        speed: 1, // Rounds per second
        trail: 22, // Afterglow percentage
        shadow: false, // Whether to render a shadow
        hwaccel: false, // Whether to use hardware acceleration
        className: 'spinner', // The CSS class to assign to the spinner
        zIndex: 2e9, // The z-index (defaults to 2000000000)
        top: 'auto', // Top position relative to parent in px
        left: 'auto' // Left position relative to parent in px
	};
	firstload = true;
	loading = document.getElementById('loading');
	spinner = new Spinner(opts).spin(loading);
	requests = 0;
	results = 0;
	xmlhttp = createXMLHttpRequest();
	sendXmlHttpRequest();
};
    </script>
  </head>
  <body>
    <div class="title">
      <img src="images/title.png"/>
    </div>
    <div class="searchform">
      <form action="/cometreviews/search">
        <input id="search" type="text" name="query" value="<%=query%>"/>
        <input id="location" type="text" name="location" value="<%=location%>"/>
        <input id="submit" type="submit" value="Search!"/>
        <div class="checkbox">
        <%
        if (cityChk) {
        %>
            <input name="CityGrid" type="checkbox" value="true" checked/>CityGrid
        <%
        } else {
        %>
            <input name="CityGrid" type="checkbox" value="true"/>CityGrid
        <%
        }
        %>
                <%
        if (yelpChk) {
        %>
            <input name="Yelp" type="checkbox" value="true" checked/>Yelp
        <%
        } else {
        %>
            <input name="Yelp" type="checkbox" value="true"/>Yelp
        <%
        }
        %>
            
        </div>
      </form>
    </div>
    
    <!--  Time is now: <%=date%> RequestId is <%=requestId%> -->
    
    <div id="results">Loading...
    </div>
    <div id="loading"></div>
    
  </body>
</html>